<?php
namespace App\Admin\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use App\Admin\Controllers\Controller;
use App\Admin\Admin;
use App\Models\User;

class OAuthController extends Controller
{
    /**
     * http://www.llc.com/api/admin/oauth/providers
     */
    public function providers()
    {
        return Admin::success([
            [
                'name' => 'github',
                'redirect' => action([self::class, 'redirect'], ['name'=>'github']),
            ],
            [
                'name' => 'authing',
                'redirect' => action([self::class, 'redirect'], ['name'=>'authing']),
            ],
            [
                'name' => 'work_weixin',
                'redirect' => action([self::class, 'redirect'], ['name'=>'work_weixin']),
            ],
            [
                'name' => 'feishu',
                'redirect' => action([self::class, 'redirect'], ['name'=>'feishu']),
            ],
            [
                'name' => 'dingtalk',
                'redirect' => action([self::class, 'redirect'], ['name'=>'dingtalk']),
            ],
        ]);
    }


    /**
     * http://www.llc.com/api/admin/oauth/authing/redirect
     * getTargetUrl
     */
    public function redirect(Request $request, $name)
    {
        // return Admin::socialite($name)->redirect()->getTargetUrl();
        return Admin::socialite($name)->redirect();
    }

    /**
     * http://www.llc.com/api/admin/oauth/github/exchange?code=1ebd4d7382652723b614
     * http://www.llc.com/api/admin/oauth/authing/exchange
     */
    public function exchange(Request $request, $name)
    {
        if( !$request->input('s') ){
            $code = $request->input('code');
            return redirect()->away("http://localhost:5173/oauth/callback?name={$name}&code={$code}");
        }


        $user = Admin::socialite($name)->user();

        return [$user];
    }
}
